package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {
    //1.获取sqlSessionFactory对象
    static SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        //2.获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取brandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        List<Brand> brands = brandMapper.selectAll();
        //5.释放资源
        sqlSession.close();
        return brands;
    }

    @Override
    public void addBrand(Brand brand) {
        //2.获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取brandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        brandMapper.addBrand(brand);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }

    @Override
    public Brand findById(String id) {
        //2.获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取brandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        Brand brand = brandMapper.findById(id);
        //5.释放资源
        sqlSession.close();
        return brand;
    }

    @Override
    public void update(Brand brand) {
        //2.获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取brandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        brandMapper.update(brand);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }

    @Override
    public void delectById(String id) {
        //2.获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取brandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        brandMapper.delectById(id);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
}
